<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { getCurrentMemberService, upgradeCurrentMemberService } from '@/api/member.js'
import { countBusinessForMemberService } from '@/api/business.js'
import { countFeedbackForMemberService } from '@/api/feedback.js'
import BalanceRecharge from '../../components/BalanceRecharge.vue'

const router = useRouter()
const userStore = useUserStore()

// 下拉刷新
const refreshLoading = ref(false)

const memberInfo = ref({
  id: null, // 会员id
  name: null, // 姓名
  avatarUrl: null, // 头像链接
  level: null, // 会员等级
  points: null, // 会员积分
  balance: null // 账户余额
})

// 徽标数
const badgeCounts = ref({
  waitFeedback: 0, // 待评价的评价数量
  unacceptedBusiness: 0, // 待接单的业务数量
  inProgressBusiness: 0 // 进行中的业务数量
})

// 获取当前会员信息
const getCurrentMember = async () => {
  const res = await getCurrentMemberService()
  memberInfo.value = res.data.data
  refreshLoading.value = false
  // 根据当前会员等级确定可升级的等级
  const currentLevelIndex = membershipLevels.findIndex(
    (level) => level.name === memberInfo.value.level
  )
  membershipLevels.forEach((level, index) => {
    level.canUpgrade = index > currentLevelIndex
  })
  const unacceptedRes = await countBusinessForMemberService('待接单')
  badgeCounts.value.unaccepted = unacceptedRes.data.data
  const inProgressRes = await countBusinessForMemberService('进行中')
  badgeCounts.value.inProgress = inProgressRes.data.data
  const waitFeedbackRes = await countFeedbackForMemberService()
  badgeCounts.value.waitFeedback = waitFeedbackRes.data.data
}
getCurrentMember()

// 会员等级升级
const membershipLevels = [
  { name: '银卡', needPoints: 648, benefits: '下单9.5折' },
  { name: '金卡', needPoints: 3240, benefits: '下单8.5折' },
  { name: '至尊', needPoints: 6480, benefits: '下单7折' }
]

// 会员等级与van-tag类型映射
const memberLevelTagTypeMap = {
  普通: 'default',
  银卡: 'primary',
  金卡: 'warning',
  至尊: 'danger'
}
const getMemberLevelTagType = (level) => {
  return memberLevelTagTypeMap[level] || 'info'
}

// 退出
const handleLogout = () => {
  showDialog({
    title: '确定要退出登录吗？',
    showConfirmButton: true,
    showCancelButton: true
  }).then(() => {
    userStore.setUser({})
    userStore.setToken('')
    showNotify({
      type: 'success',
      message: '已退出登录'
    })
    router.push('/login')
  })
}

// 业务跳转
const goBusiness = (businessStatus) => {
  router.push({
    path: '/user/business',
    query: { businessStatus }
  })
}

// 余额充值
const balanceRechargeRef = ref()
const handleBalanceRecharge = (memberInfo) => {
  balanceRechargeRef.value.open(memberInfo)
}

// 会员等级升级
const selectedMemberLevel = ref()
const handleUpgradeMemberLevel = async (newLevel) => {
  selectedMemberLevel.value = newLevel
  showDialog({
    title: `确定升级到${selectedMemberLevel.value}会员吗？`,
    showConfirmButton: true,
    showCancelButton: true
  }).then(async () => {
    await upgradeCurrentMemberService(selectedMemberLevel.value)
    showNotify({
      type: 'success',
      message: '升级成功'
    })
    getCurrentMember()
  })
}
</script>

<template>
  <div class="user-home">
    <van-nav-bar title="会员中心" right-text="退出登录" @click-right="handleLogout" fixed />
    <van-pull-refresh v-model="refreshLoading" @refresh="getCurrentMember" success-text="加载成功">
      <!-- 会员信息卡片 -->
      <div class="user-card">
        <div class="user-info">
          <van-image round width="50" height="50" :src="memberInfo.avatarUrl" class="avatar" />
          <div class="user-details">
            <div class="name-type">
              <span class="name">{{ memberInfo.name }}</span>
              <van-tag :type="getMemberLevelTagType(memberInfo.level)">{{
                memberInfo.level
              }}</van-tag>
            </div>
            <div class="member-number">会员ID：{{ memberInfo.id }}</div>
          </div>
          <van-icon name="qr" size="24" class="qr-code" />
        </div>
        <div class="balance-info">
          <div class="balance" @click="handleBalanceRecharge(memberInfo)">
            <span class="amount">{{ (memberInfo.balance / 100).toFixed(2) }}</span>
            <span class="label">余额（元）</span>
          </div>
          <div class="points">
            <span class="point">{{ memberInfo.points }}</span>
            <span class="label">积分</span>
          </div>
        </div>
      </div>

      <!-- 会员升级 -->
      <div>
        <h3 class="section-title">会员升级</h3>
        <div class="membership-cards">
          <div
            class="membership-card"
            v-for="level in membershipLevels"
            :key="level.name"
            @click="level.canUpgrade ? handleUpgradeMemberLevel(level.name) : null"
            :class="{ disabled: !level.canUpgrade }"
          >
            <div class="level-name">{{ level.name }}会员</div>
            <div class="need-points">
              <span class="points-number">{{ level.needPoints }}</span>
              <span class="text">积分</span>
            </div>
            <div class="benefits">{{ level.benefits }}</div>
            <!-- 蒙版 -->
            <div v-if="!level.canUpgrade" class="overlay"></div>
          </div>
        </div>
      </div>

      <!-- 个人中心 -->
      <div class="own-section">
        <h3 class="section-title">个人中心</h3>
        <van-grid :column-num="4" :border="false">
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="user_management"
            text="个人资料"
            @click="router.push('/user/info')"
          />
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="car"
            text="车辆管理"
            @click="router.push('/user/car')"
          />
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="feedback"
            text="服务评价"
            :badge="badgeCounts.waitFeedback"
            :badge-props="{ showZero: false }"
            @click="router.push('/user/feedback')"
          />
        </van-grid>
      </div>

      <!-- 我的业务 -->
      <div class="order-section">
        <h3 class="section-title">我的业务</h3>
        <van-grid :column-num="5" :border="false">
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="unaccepted"
            text="待接单"
            :badge="badgeCounts.unaccepted"
            :badge-props="{ showZero: false }"
            @click="goBusiness('待接单')"
          />
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="on_service"
            text="进行中"
            :badge="badgeCounts.inProgress"
            :badge-props="{ showZero: false }"
            @click="goBusiness('进行中')"
          />
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="completed"
            text="已完成"
            @click="goBusiness('已完成')"
          />
          <van-grid-item
            class="iconfont"
            icon-prefix="icon"
            icon="refunded"
            text="已退款"
            @click="goBusiness('已退款')"
          />
        </van-grid>
      </div>
    </van-pull-refresh>
  </div>
  <!-- 余额充值弹出层 -->
  <balance-recharge ref="balanceRechargeRef" @success="getCurrentMember"></balance-recharge>
</template>

<style lang="scss" scoped>
.user-home {
  padding-top: 46px;
  padding-bottom: 50px;
  background-color: #f7f8fa;
  min-height: 100vh;

  .user-card {
    margin: 16px;
    padding: 20px;
    background: linear-gradient(135deg, #8bbfff 0%, #2d7fff 100%);
    border-radius: 12px;
    color: #fff;

    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .user-details {
        flex: 1;
        margin-left: 12px;

        .name-type {
          display: flex;
          align-items: center;
          margin-bottom: 4px;

          .name {
            font-size: 18px;
            font-weight: 600;
            margin-right: 8px;
          }
        }

        .member-number {
          font-size: 12px;
          opacity: 0.8;
        }
      }
    }

    .balance-info {
      display: flex;
      text-align: center;

      .balance,
      .points {
        flex: 1;

        .amount,
        .point {
          display: block;
          font-size: 24px;
          font-weight: 600;
          margin-bottom: 4px;
        }

        .label {
          font-size: 12px;
          opacity: 0.8;
        }
      }
    }
  }

  .section-title {
    margin: 16px;
    font-size: 16px;
    font-weight: 600;
  }

  .membership-cards {
    display: flex;
    padding: 0 16px;
    gap: 12px;

    .membership-card {
      flex: 0 0 auto;
      width: 105px;
      padding: 16px;
      background-color: #fff;
      border: 1px solid rgba(0, 0, 0, 0.1);
      border-radius: 10px;
      text-align: center;
      position: relative;
      cursor: pointer;

      &.disabled {
        cursor: not-allowed;
        opacity: 0.5;
      }

      .overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(255, 255, 255, 0.5);
        z-index: 1;
      }

      .level-name {
        font-size: 14px;
        margin-bottom: 8px;
      }

      .need-points {
        display: flex;
        align-items: baseline;
        justify-content: center;
        color: #ff6b6b;
        margin-bottom: 8px;

        .points-number {
          font-size: 20px;
          font-weight: 600;
        }

        .text {
          font-size: 12px;
          margin-left: 2px;
        }
      }

      .need-points {
        font-size: 22px;
        font-weight: 600;
        color: #ff6b6b;
        margin-bottom: 8px;
      }

      .benefits {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .order-section,
  .own-section {
    margin-top: 20px;
    background-color: #fff;
    padding: 1px 0 16px 0;
  }
}
</style>
